package lrl.nsfw.user.service.impl;

import java.io.File;
import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;

import org.springframework.stereotype.Service;

import lrl.core.util.ExcelUtil;
import lrl.nsfw.role.entity.Role;
import lrl.nsfw.user.dao.UserDao;
import lrl.nsfw.user.entity.User;
import lrl.nsfw.user.entity.UserRole;
import lrl.nsfw.user.entity.UserRoleId;
import lrl.nsfw.user.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserDao userDao;
	
	@Override
	public void save(User user) {
		userDao.save(user);

	}

	@Override
	public void update(User user) {
		userDao.update(user);

	}

	@Override
	public void delete(Serializable id) {
		userDao.delete(id);

	}

	@Override
	public User findObjectById(Serializable id) {

		return userDao.findObjectById(id);
	}

	@Override
	public List<User> findObjects() {
		
		return userDao.findObjects();
	}

	@Override
	public void exportExcel(List<User> userList,
			ServletOutputStream outputStream) {
		ExcelUtil.exportUserExcel(userList, outputStream);
		
	}

	@Override
	public void importExcel(File userExcel, String userExcelFileName) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<User> findUserByAccountAndId(String account, String id) {

		return userDao.findUserByAccountAndId(account, id);
	}

	@Override
	public void saveUserAndRole(User user, String[] userRoleIds) {
		// TODO Auto-generated method stub
		save(user);
		if (userRoleIds != null) {
			for (String roleId : userRoleIds) {
				userDao.saveUserRole(new UserRole(new UserRoleId(new Role(roleId), user.getId())));
			}
		}
	}

	@Override
	public List<UserRole> getUserRolesByUserId(String id) {
			return userDao.getUserRolesByUserId(id);
	}

	@Override
	public void updateUserAndRole(User user, String[] userRoleIds) {
		//1、根据用户删除该用户的所有角色
		userDao.deleteUserRoleByUserId(user.getId());
		//2、更新用户
		update(user);
		//3、保存用户对应的角色
		if(userRoleIds != null){
			for(String roleId: userRoleIds){
				userDao.saveUserRole(new UserRole(new UserRoleId(new Role(roleId), user.getId())));
			}
		}
	}

	@Override
	public List<User> findUserByAccountAndPass(String account, String password) {

		return userDao.findObjectsByAccountAndPass(account, password);
	}



}
